﻿using IOA.MES.TcpService.Models;
using IOA.Utils;
using log4net;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Config;
using SuperSocket.SocketBase.Protocol;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;

namespace IOA.MES.TcpService.WeldingService
{
    public class WeldingServer : AppServer<WeldingSession, BinaryRequestInfo>
    {
        private ILog logger = LogManager.GetLogger(nameof(WeldingReceiveFilter));
        public WeldingServer() : base(new WeldingReceiveFilterFactory()) { }

        protected override bool Setup(IRootConfig rootConfig, IServerConfig config)
        {
            this.NewRequestReceived += ElectricMeterServer_NewRequestReceived;
            return base.Setup(rootConfig, config);
        }

        private void ElectricMeterServer_NewRequestReceived(WeldingSession session, BinaryRequestInfo requestInfo)
        {
            var stopWatcher = new Stopwatch();
            var requestStr = ByteUtils.HexToString(requestInfo.Body);
            logger.Warn($"{session.RemoteEndPoint.ToString()} 接收消息：{requestStr}");
            stopWatcher.Start();
            var message = new List<byte>();
            try
            {
                var request = new
                {
                    ClientIpHost = session.RemoteEndPoint.Address.ToString(),
                    Data = requestInfo.Body.ToList()
                };
                var responseStr = new HttpHelper().PostJson($"{ConfigurationManager.AppSettings["ServerApiRoot"]}/api/Welding/PlcHandle", request);
                Logger.Warn($"{session.RemoteEndPoint.ToString()} 请求Api：{JsonUtils.Serialize(request)}，Api返回：{responseStr}");
                var response = JsonUtils.Deserialize<BaseResponse<List<byte>>>(responseStr);
                message = response.Data;
            }
            catch (Exception ex)
            {
                logger.Fatal($"RequestReceived异常：{ex.Message}", ex);
            }
            if (message.Any())
            {
                SendMessage(session, message);
            }
            stopWatcher.Stop();
            logger.Warn($"{session.RemoteEndPoint.ToString()} 报文处理耗时：{stopWatcher.ElapsedMilliseconds}，报文：{requestStr}");
        }

        private void SendMessage(WeldingSession session, List<byte> message)
        {
            session.Send(message.ToArray(), 0, message.Count);
            Logger.Warn($"{session.RemoteEndPoint.ToString()} 发送报文：{ByteUtils.HexToString(message.ToArray())}");
        }
    }
}
